package hd.util.http;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.List;

/**
 * ApiClient 用于Http请求
 * <p/>
 * Created by haidy on 14/12/14.
 */
public class ApiClient {

    /**
     * 连接超时
     */
    public final static String ConnectTimeOut = "连接超时！";
    /**
     * 连接获取数据超时
     */
    public final static String SocketTimeOut = "获取数据超时！";
    /**
     * 网络异常
     */
    public final static String ConnectException = "网络异常！";
    /**
     * 连接失败
     */
    public final static String ConnectDefeated = "连接失败！";

    public final static String UnknownError = "未知错误";

    /**
     * 连接成功
     */
    public final static String OK = "ok";

    public static final String FAILURE = "failure";// 失败

    /**
     * 判断是否成功链接服务器
     *
     * @return 是否连接服务器
     */
    public static boolean isConnect(String s) {
        return !s.equals(ConnectTimeOut) && !s.equals(SocketTimeOut)
                && !s.equals(ConnectException) && !s.equals(ConnectDefeated);
    }

    public static String httpGet(String url, Header[] headers, String requestCharset, String responseCharset) {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20 * 1000);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20 * 1000);
        HttpGet get = new HttpGet(url);
        get.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        if (headers != null) {
            get.setHeaders(headers);
        }
        try {
            HttpResponse httpResponse = client.execute(get);
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return ConnectDefeated;
            } else {
                return EntityUtils.toString(httpResponse.getEntity(), responseCharset);
            }
        } catch (ConnectTimeoutException e) {// 连接超时抛出异常
            return ConnectTimeOut;
        } catch (SocketTimeoutException e) {
            return SocketTimeOut;
        } catch (Exception e) {
            return ConnectException;
        } finally {
            client.getConnectionManager().shutdown();
        }
    }

    public static String httpPost(String url, Header[] headers, List<NameValuePair> pairs, String requestCharset, String responseCharset) {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20 * 1000);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20 * 1000);
        HttpPost post = new HttpPost(url);
        post.setHeaders(headers);
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, requestCharset);
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        post.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        HttpResponse httpResponse;
        try {
            httpResponse = client.execute(post);

            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return ConnectDefeated;
            } else {
                return EntityUtils.toString(httpResponse.getEntity(), responseCharset);
            }
        } catch (ConnectTimeoutException e) {// 连接超时抛出异常
            return ConnectTimeOut;
        } catch (SocketTimeoutException e) {
            return SocketTimeOut;
        } catch (Exception e) {
            return ConnectException;
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
}
